<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="title" width="660px">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
      <el-form-item label="按钮名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="按钮编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="所属菜单">
        <el-cascader
          style="width: 500px"
          :value="parentIds"
          placeholder="根节点"
          :options="parents"
          clearable=""
          filterable
          change-on-select
          @change="handleParentIdChange"
        />
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input v-model="form.description" placeholder="请输入内容" />
      </el-form-item>

      <el-form-item label="权限" prop="permList">
        <el-select v-model="form.permList" style="width: 500px" filterable multiple placeholder="请选择">
          <el-option-group
            v-for="group in groupList"
            :key="group.groupId"
            class="option-group"
            :label="group.groupName"
          >
            <el-option
              v-for="item in group.permInfos"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="需要全部权限" prop="needAllPerms">
        <el-checkbox v-model="form.needAllPerms" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="hide">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addResource,
  getResource,
  updateResource
} from '@/api/resource'
import { findParent, menusTreeToList, transToOptions } from '@/utils/menusUtil'
import { getGroupPerms } from '@/api/perm'

export default {
  props: {
    scope: {
      require: true,
      type: Number
    }
  },
  data() {
    return {
      methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
      typeOptions: [{
        id: 0,
        name: 'button'
      }, {
        id: 1,
        name: 'uri'
      }],
      resolve: null,
      reject: null,
      mode: null,
      loading: false,
      title: null,
      dialogVisible: null,
      parents: [],
      groupList: [],
      parentIds: [],
      parentId: -1,
      form: {
        code: undefined,
        type: undefined,
        permList: [],
        name: undefined,
        uri: undefined,
        parentId: undefined,
        needAllPerms: undefined,
        method: undefined,
        description: undefined
      },
      rules: {
        code: [{
          required: true,
          message: '请输入资源编码',
          trigger: 'blur'
        }
        ],
        permList: [{
          required: true,
          message: '请选择权限',
          trigger: 'blur'
        }
        ],
        type: [{
          required: true,
          message: '请输入资源类型',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'blur'
        }
        ],
        name: [{
          required: true,
          message: '请输入资源名称',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'blur'
        }
        ],
        uri: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ],
        method: [{
          required: true,
          message: '请输入资源请求类型',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ]
      }
    }
  },

  methods: {
    defaultForm() {
      return {
        code: undefined,
        type: 1,
        parentIds: [],
        permList: [],
        name: undefined,
        uri: undefined,
        parentId: undefined,
        method: undefined,
        needAllPerms: true,
        description: undefined
      }
    },

    fetchData() {
      this.loading = true
      return getResource(this.resourceId, this.scope).then((res) => {
        this.loading = false
        if (res.code === 0) {
          this.form = res.data
          this.parentId = res.data.parentId
        } else {
          this.$message.error(res.msg)
        }
      }).catch((error) => {
        console.error('getMenuInfo error', error)
        this.loading = false
      })
    },
    openAdd(parentId, treeData) {
      this.mode = 'add'
      this.title = '新增按钮'
      this.resourceId = null
      this.form = this.defaultForm()
      this.form.parentId = parentId
      this.parentId = parentId
      this.transformTree(treeData, parentId)

      getGroupPerms(this.scope).then(res => {
        this.groupList = res.data
      })
      this.show()

      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },
    openEdit(resourceId, treeData) {
      this.title = '编辑按钮'
      this.resourceId = resourceId
      this.mode = 'edit'
      this.groupList = []
      this.form = this.defaultForm()

      getGroupPerms(this.scope).then(res => {
        this.groupList = res.data
        this.show()
        this.fetchData().then(() => {
          this.transformTree(treeData)
        })
      })

      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.dialogVisible = false
    },

    transformTree(treeData) {
      const parents = transToOptions(treeData, null, true)
      if (this.form.parentId) {
        const mList = menusTreeToList(parents)
        const ps = findParent(mList, this.form.parentId)
        const parentIds = []
        for (let i = 0; i < ps.length; i++) {
          parentIds.push(ps[i].id)
        }
        this.parentIds = parentIds
      } else {
        this.parentIds = []
      }
      console.info('parents', parents)
      this.parents = parents || []
    },
    handleParentIdChange(value) {
      if (value.length > 0) {
        this.parentId = value[value.length - 1]
      } else {
        this.parentId = -1
      }
    },
    updateResource() {
      this.form.parentId = this.parentId
      return updateResource(this.resourceId, this.form, this.scope).then((res) => {
        if (res.code === 0) {
          this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
          this.hide()
          this.resolve && this.resolve()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    addResource() {
      this.form.parentId = this.parentId
      return addResource(this.form, this.scope).then((res) => {
        if (res.code === 0) {
          this.$notify({ title: '成功', message: '添加成功', type: 'success', duration: 2000 })
          this.hide()
          this.resolve && this.resolve()
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.mode === 'edit') {
            this.updateResource()
          } else {
            this.addResource()
          }
        } else {
          this.$message.error('请按要求填写好表格.')
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .option-group ::v-deep .el-select-group__title {
    padding-left: 20px;
    font-size: 10px;
    color: #c0c4cc;
    line-height: 30px;
  }
</style>
